<?php

declare (strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * @property int $id
 * @property int $user_id
 * @property string $detail
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property int $role
 * @property int $flag
 */
class UserAvatarLog extends Model
{
    const FLAG_OK = 1;

    //不可操作
    const FLAG_NO = 0;

    //违规
    const FLAG_BAD = -1;

    //审核中
    const FLAG_ING = 2;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user_avatar_log';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'role', 'detail', 'flag'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'user_id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'flag' => 'integer'];

    /**
     * 添加记录
     * @param int $userId
     * @param string $detail
     * @param int $status
     * @return UserAvatarLog|false|\Hyperf\Database\Model\Model
     */
    static function addRecord(
        int    $userId = 0,
        string $detail = '',
        int    $status = self::FLAG_OK
    )
    {
        $where = ['user_id' => $userId];
        $last = self::where($where)->orderBy('id', 'desc')->first();
        if ($last && $last->detail == $detail) {
            return false;
        }

        $where['flag'] = self::FLAG_OK;
        self::where($where)->update(['flag' => self::FLAG_NO]);

        $role = UserProfile::getRoleByUserId($userId) ?? UserProfile::ROLE_USER;

        return self::create([
            'user_id' => $userId,
            'role' => $role,
            'detail' => $detail,
            'flag' => $status,
        ]);
    }
}